<?php

namespace Modules\Car\Http\Controllers\Api;

use App\Events\RecivedCarEvent;
use App\Helpers\Constant;
use App\Helpers\NewBaseData;
use App\Helpers\PayTrait;
use App\Helpers\ResponseData;
use App\Jobs\CloseOrder;
use App\Models\CarService;
use App\Models\Order\LeaseChangeLog;
use App\Models\Order\RenewLease;
use App\Models\PayLog;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\DB;
use Modules\Car\Entities\CarOrder;
use Modules\Car\Entities\RecognizeDrivingLicense;
use Modules\Car\Http\Requests\Api\PlaceRequest;
use App\Events\NotifyEvent;
use Modules\Manager\Entities\Department;
use Modules\Car\Entities\Customer;
use App\Http\Controllers\Wx\SendTemplateController;
use Modules\Manager\Entities\Manager;
use App\Models\AttendanceStatistics;

//用户下单
class PlaceController extends Controller
{
    use NewBaseData,ResponseData,PayTrait;
    public $req;
    //预订单
    public function preparatory(PlaceRequest $request){
        $this->req = $request;
        $user = $request->user();
        // if(!$user->post_id){
        //     return $this->failed('请使用店长或小程序用户下单',201);
        // }
        // 获取车辆
        $this->car = $this->seriesCar($request->car_series_id);
        // 计算总计
        $data = $this->totalPrice($request);
        $data['days'] = $this->days;
        $data['hours'] = $this->hours;
        //押金
        if($request->filled('deposit')){
            $deposit = $request->deposit;
        }else{
            $deposit = $this->car->deposit;
        }
        //违章押金
        if($request->filled('break_rules')){
            $break_rules = $request->break_rules;
        }else{
            $break_rules = $this->car->break_rules;
        }

        //总押金
        $all_deposit = $deposit+$break_rules;
        $acc_total = $data['bc_service_total']+$data['bc_base_price_total']+$data['bc_brokerage_total']+$data['bc_lease_price_total'];
        $bc_total = $acc_total+$all_deposit;
        // if($request->filled('change_price')){
        //     if($request->change_price<=0){
        //         return $this->failed('优惠价格填写错误',201);
        //     }else{
        //         $bc_total = $bc_total-$request->change_price;
        //     }
        // }
        //设置优惠券
        $data['coupon_price'] = 0;
        if($this->coupon&&$request->filled('coupon')&&$request->coupon>0){
            $data['coupon_price'] = $this->coupon->price;
        }
        //组合数据
        $array = $this->getData($request,$data,$deposit,$break_rules,$bc_total);
        $array['status'] = Constant::ORDER_IS_CONFIRM;//已确认订单状态
        $array['create_order_category'] = Constant::PERPARATORY;//预订单

        $array['system_total'] = $request->system_total??0.00;
        $array['change_price'] = $request->change_price??0.00;
        $array['userid'] = $request->userid??0;
        $array['customer_id'] = $request->customer_id??0;
        $array['role'] = $user->post_id??1;
        $license_number = $request->input('license_number','');//证件号
        if($license_number){
            $array['license_number'] = $license_number;
        }

        if($request->filled('gear_car_id')){
            $is_car = RecognizeDrivingLicense::query()->find($request->gear_car_id);
            $array['plate_number'] = $is_car->plate_number??'';
        }
        // $array['fetch_time'] = now();
        if($request->filled('fact_pay')){
            $array['fact_pay'] = $request->fact_pay;
        }
        $array['unpaid_amount'] = $request->input('unpaid_amount',0.00);
        $array['order_mark'] = $request->input('order_mark','');
        if($request->filled('deport_status')){
            $array['deport_status'] = $request->deport_status;
        }
        if($request->filled('break_rules_status')){
            $array['break_rules_status'] = $request->break_rules_status;
        }
        if($request->filled('is_change_car')){
            $array['is_change_car'] = $request->is_change_car;
        }
        if($request->filled('contract_day_price')){
            $array['contract_day_price'] = $request->contract_day_price;
        }
        DB::beginTransaction();
        $order = CarOrder::query()->create($array);
        $order->service()->createMany($this->orderService($request->service,$this->daily,$this->car));

        $isCar = RecognizeDrivingLicense::query()->find($order->gear_car_id);
        if($isCar){
            $isCar->is_used = 1;
            $isCar->use_status =8;
            $isCar->save();
        }
        if(!$order){
            DB::rollBack();
            return $this->failed('订单创建错误',201);
        }
        $log = [
            'order_sn'=>  $order['order_sn'],
            'real_pay'=>$order['total'],
        ];
        PayLog::create($log);
        DB::commit();
        //下单通知
        return $this->success("请求成功");
    }
    //立即出车
    public function create(PlaceRequest $request){
        $this->req = $request;
        $user = $request->user();
        // 获取车辆
        $this->car = $this->seriesCar($request->car_series_id);
        // 计算总价
        $data = $this->totalPrice($request);
        $data['days'] = $this->days;
        $data['hours'] = $this->hours;
        //押金
        if($request->filled('deposit')){
            $deposit = $request->deposit;
        }else{
            $deposit = $this->car->deposit;
        }
        //违章押金
        if($request->filled('break_rules')){
            $break_rules = $request->break_rules;
        }else{
            $break_rules = $this->car->break_rules;
        }
        //总押金
        $all_deposit = $deposit+$break_rules;
        $acc_total = $data['bc_service_total']+$data['bc_base_price_total']+$data['bc_brokerage_total']+$data['bc_lease_price_total'];
        $bc_total = $acc_total+$all_deposit;
        //设置优惠券
        $data['coupon_price'] = 0;
        if($this->coupon&&$request->filled('coupon')&&$request->coupon>0){
            $data['coupon_price'] = $this->coupon->price;
        }
        //组合数据
        $array = $this->getData($request,$data,$deposit,$break_rules,$bc_total);
        $array['status'] = Constant::ORDER_USING;//直接使用中
        $array['create_order_category'] = Constant::CUSTOM_ORDER;//直接使用订单
        $array['gear_car_id'] = $request->gear_car_id;//车辆id
        $array['init_car_series_id'] = $request->car_series_id;//车辆id
        $array['gear_car_name'] = $request->gear_car_name;//车名称
        $array['system_total'] = $request->system_total??0.00;
        $array['change_price'] = $request->change_price??0.00;
        $array['userid'] = $request->userid??0;
        $array['customer_id'] = $request->customer_id??0;
        $array['role'] = $user->post_id??1;
        $license_number = $request->input('license_number','');//证件号
        if($license_number){
            $array['license_number'] = $license_number;
        }

        if($request->filled('send_mileage')){
            $array['send_mileage'] = $request->send_mileage;
        }
        if($request->filled('send_employer_nickname')){
            $array['send_employer_nickname'] = $request->send_employer_nickname;
        }
        if($request->filled('gear_car_id')){
            $is_car = RecognizeDrivingLicense::query()->find($request->gear_car_id);
            $array['plate_number'] = $is_car->plate_number??'';
        }
        // $array['fetch_time'] = now();
        if($request->filled('fact_pay')){
            $array['fact_pay'] = $request->fact_pay;
        }
        $array['unpaid_amount'] = $request->input('unpaid_amount',0.00);
        $array['order_mark'] = $request->input('order_mark','');
        $array['process_status'] = 1;
        if($request->filled('deport_status')){
            $array['deport_status'] = $request->deport_status;
        }
        if($request->filled('break_rules_status')){
            $array['break_rules_status'] = $request->break_rules_status;
        }
        if($request->filled('is_change_car')){
            $array['is_change_car'] = $request->is_change_car;
        }
        if($request->filled('contract_day_price')){
            $array['contract_day_price'] = $request->contract_day_price;
        }
        $isCar = RecognizeDrivingLicense::query()->find($request->gear_car_id);
        if($isCar&&$isCar->is_used!=0){
            return $this->failed('当前车辆已出车，请更换车辆',201);
        }
        if($isCar){
            $isCar->is_used = 1;
            $isCar->use_status =8;
            $isCar->save();
        }
        DB::beginTransaction();
        info('下单数据'.json_encode($array));
        $order = CarOrder::query()->create($array);

        $order->service()->createMany($this->orderService($request->service,$this->daily,$this->car));
        // 出车统计事件
        event(new RecivedCarEvent($order));
        if(!$order){
            DB::rollBack();
            return $this->failed('订单创建错误',201);
        }
        $log = [
            'order_sn'=>  $order['order_sn'],
            'real_pay'=>$order['total'],
        ];
        PayLog::create($log);
        DB::commit();
        //下单通知
        return $this->success("请求成功");
    }

    //小程序下单接口
    public function createMini(PlaceRequest $request){
        $this->req = $request;
        // 获取车辆
        $this->car = $this->seriesCar($request->car_series_id);
        // 计算总计
        $data = $this->totalPrice($request);
        //计算总押金
        list($bc_total,$deposit,$break_rules) = $this->computeBcTotal($request,$data);
        info('或到的bc_total'.$bc_total);
        //组合订单数据
        $data['coupon_price'] = 0;
        if($this->coupon&&$request->filled('coupon')&&$request->coupon>0){
            $data['coupon_price'] = $this->coupon->price;
        }
        $array = $this->getData($request,$data,$deposit,$break_rules,$bc_total);
        $array['openid'] = $request->openid??0;
        $array['yxhd_id'] = $request->yxhdid??0;
        $array['yxhd_rate'] = $request->yxhdrate??1;
        if($request->filled('deport_status')){
            $array['deport_status'] = $request->deport_status;
        }
        if($request->filled('break_rules_status')){
            $array['break_rules_status'] = $request->break_rules_status;
        }
        // 如果当前下单客户在系统内匹配到了，写入顾客ID
        $customer = Customer::query()->where('phone',$request->phone)->where('openid',$request->openid)->first();
        if ($customer) {
            $array['customer_id'] = $customer['id'];
        }
        info('获取订单数据',$array);
//        return $this->success($array);
        DB::beginTransaction();
        $order = CarOrder::query()->create($array);
        $order->service()->createMany($this->orderService($request->service,$this->daily,$this->car));
        CloseOrder::dispatch($order)->delay(env('CLOSE_ORDER_TIME',1800));
        if(!$order){
            DB::rollBack();
            return $this->failed('订单创建错误',201);
        }
        $log = [
            'order_sn'=>  $order['order_sn'],
            'real_pay'=>$order['total'],
        ];
        PayLog::create($log);
        DB::commit();
        $result = $this->miniv2Data($order);
        //下单通知（小程序）
        event(new NotifyEvent($order,config('wechat.notify.mini.TradeCreate')));
        //下单通知（公众号）
        $manager = Manager::query()->where('department_id',$array['department'])->where('post_id',2)->first();
        $departmentInfo = Department::query()->where('id',$array['department'])->first();
        if ($manager&&$manager['wechat_openid']) {
            $tempmsg = [
                'wechat_openid'=>$manager['wechat_openid'],
                'orderType'=>'未支付订单提醒: '.$departmentInfo['name'].'店有意向客户浏览，请及时关注',
                'customerInfo'=>$array['wx_name'],
                'page'=>'pages/admin/home/home',
            ];
            if ($customer) {
                $tempmsg['customerInfo'] = $customer['name'];
            }
            (new SendTemplateController())->sendTemplateNewOrder($tempmsg);
            info(json_encode($tempmsg));
        }
        return $this->success($result);
    }
//    private function getCoupon($bc_total){
//        $data['is_coupon'] = 1;//启用优惠券
//        $data['coupon_id'] = $this->coupon->id;
//        $data['coupon_price'] = $this->coupon->price;
//        $this->coupon->status = 1;
//        $this->coupon->save();
//        return $bc_total-$this->coupon->price;
//    }
    // 获取最后一次分配的店铺
    protected function searchLastDepartment($request,$order_sn){
        // 总店的ID现在是1
        if($request->department==1){
            // 获取允许分配的门店数据列表
            $list = Department::query()->where('order_auto_assign',1)->orderBy('id')->pluck('id')->toArray();
            if (count($list) > 0) {
                $res = $list[0];
                // 最后一个已分配的部门ID
                $value = LeaseChangeLog::query()->latest()->value('department');
                if($value){
                    $key = array_search($value, $list);
                    if (($key+1) >= count($list)) {
                        $res = $list[0];
                    } else {
                        $res = $list[$key+1];
                    }
                }
                if($request->filled('openid')){
                    $user = User::query()->where('openid',$request->openid)->first();
                    if($user){
                        $user->department = $res;
                        $user->save();
                    }
                }
                LeaseChangeLog::query()->create(['department'=>$res,'order_sn'=>$order_sn]);
                return $res;
            } else {
                return $request->department;
            }
        }else{
            return $request->department;
        }

    }
    //设置订单数据
    private function getData($request,$data,$deposit,$break_rules,$bc_total){
        if($request->filled('additional_services_price')){
            $bc_total +=$request->additional_services_price;
        }
        $order_sn = $this->getSn();
        return [
            'coupon_price'=>$data['coupon_price'],
            'order_sn'=>$order_sn,
            'source'=>$request->source?:'总部',
            'wx_name'=>$request->wx_name,//姓名
            'phone'=>$request->phone,//电话
            'mini_phone'=>$request->mini_phone,//小程序电话
            'position'=>$request->position,//预取车地点
            'return_position'=>$request->return_position,//预还车地点
            'drink'=>$request->drink,//随车饮料
            'base_price'=>$this->base_price,//基本保障费
            'brokerage'=>$data['bc_brokerage_total'],//车辆整备费
            'lease_price'=>$this->daily_price,//日租金
            'total'=>$data['bc_total'],//预付总计金额
            'last_lease_price'=>$data['pre_total'],//改价前的租金
            'pre_fetch_time'=>$request->pre_fetch_time,//起始日期
            'pre_return_time'=>$request->pre_return_time,//终止日期
            'rate'=>$this->rate??1,//折扣
            'lease_total_price'=>0,//实际租金总价
            'deposit'=>$deposit,//租车押金
            'break_rules'=>$break_rules,//违章押金
            'car_series_id'=>$request->car_series_id,//车系id
            'init_car_series_id'=>$request->car_series_id,//车系id
            'pre_lease_days_init'=>$this->daily+$this->daily_cj,
            'pre_lease_days'=>$this->daily+$this->daily_cj,
            'name'=>$this->car->name, //车型名称
            'pre_base_price_total'=>$data['pre_base_price_total'],
            'pre_brokerage_total'=>$data['pre_brokerage_total'],
            'pre_lease_price_total'=>$data['pre_lease_price_total'],
            'pre_total'=>$data['pre_total'],
            'bc_base_price_total'=>$data['bc_base_price_total'],
            'bc_brokerage_total'=>$data['bc_brokerage_total'],
            'bc_lease_price_total'=>$data['bc_lease_price_total'],
            'bc_total'=>$bc_total,
            'car_series'=>$request->service?:0,//车所选择的服务
            'service_price'=>$data['bc_base_price_total'],//基本保障费
            'pre_service_total'=>$data['pre_service_total'],
            'bc_service_total'=>$data['bc_service_total'],
            'service'=>$request->input('service',null),
            'nickname'=>$request->nickname??null,
            'avatar'=>$request->avatar??null,
            'department'=>$this->searchLastDepartment($request,$order_sn),
            'mark'=>$request->mark??null,
            'pre_hours_init'=>$this->hours,
            'pre_hours'=>$this->hours,
            'deposit_used'=>$request->deposit_used??1,
            'break_rules_used'=>$request->break_rules_used??1,

            'car_category'=>$this->car->category,
            'pay_type'=>$request->pay_type?:'',
            'days'=>$this->days,

            'vip_service'=>$this->vip_service,//尊享无忧
            'worry_fee'=>$this->worry_fee,//车行无忧
            'paint_finish'=>$this->paint_finish,//漆面无忧
            'activity_type'=>$request->activity_type??0,
            'additional_services'=>$request->additional_services??null,
            'additional_services_price'=>$request->additional_services_price??0.00,
            'violation_amount'=>$request->violation_amount??0.00,
            'get_true_deport'=>$request->get_true_deport??0.00,
            'openid_customer'=>$request->openid_customer?:'',
        ];
    }
    //设置订单号
    private function getSn(){
        $car = CarOrder::query()
            ->select('id')
            ->where('id','>',0)
            ->orderByDesc('id')
            ->first();
        if($car){
            $num = $car->id+1;
        }else{
            $num = 1;
        }
        return date('Ymd',time()).$num;
    }
    //续租
    public function extendLease(Request $request){
        // 续租只做记录
    //     $add_day = $request->input('add_day',1);
    //     $order = CarOrder::query()->where('order_sn',$request->order_sn)
    //         ->where('status',5)
    //         ->first();
    //     if(!$order){
    //         return $this->failed('订单不存在',201);
    //     }
    //     $diffSecond = strtotime($order->pre_return_time)+$add_day*24*3600;

    //     request()->offsetSet('pre_return_time',date("Y-m-d H:i:s",$diffSecond));
    //     request()->offsetSet('pre_fetch_time',$order->pre_fetch_time);

    //     // 获取车辆
    //     $this->car = $this->seriesCar($order->car_series_id);
    //     //总计价格
    //     $data = $this->totalPrice($request);
    //     $rate = $this->rate;
    //     //计算精品服务
    //     $jp_price = 0;
    //     if($order->service&&is_string($order->service)){
    //         $jp = $this->services($order->service);
    //         $jp_price = $jp*($add_day+$order->days);
    //     }
    //     //续租基础价格
    //     $base_price = $order->lease_price*$rate*($add_day+$order->days);
    //     //应付 精品价格+基础价格
    //    // $price =$jp_price+$base_price;
    //     $order->add_days = $add_day;

    //     $order->extend_lease_type = $request->type;
    //     $days = Carbon::parse($order->pre_return_time)->addDays($add_day);
    //     $order->pre_return_time = $days;

    //     $order->lease_rate = $this->rate;
    //     //计算总押金
    //     $all = $this->allPrice($order,$base_price,$jp_price);
    //     $order->extend_lease_price = $all-$order->bc_total;
        // 续租记录
        $order = CarOrder::query()->where('order_sn',$request->order_sn)->first();
        $order->pre_return_time = $request->pre_return_time;
        $order->pre_lease_days = $request->pre_lease_days;
        $order->pre_hours = $request->pre_hours;
        $order->settle_lease_price = round($order->settle_lease_price+$request->money, 2);
        $leaseLog = [
            'order_sn'=>$order->order_sn,
            'user_name'=>$request->input('user_name',''),
            'type'=>$request->type,
            'money'=>$request->input('money','0.00'),
            'renew_starttime'=>$request->renew_starttime,
            'renew_overtime'=>$request->pre_return_time,
            'user_id'=>$request->input('user_id',0),
            'gear_car_id'=>$request->input('gear_car_id',0)
          ];

        $renew = RenewLease::query()->create($leaseLog);
        // 续租如果有取车单，需要直接删除
        $dataitem = AttendanceStatistics::query()->whereIn('type', [1,6])->where('order_sn',$order->order_sn)->first();
        if($dataitem){
            $dataitem->delete();
        }
        // 变为用车中
        $order->is_send_return_order = 1;
        // 清除取车人信息
        $order->return_employer_id = 0;
        $order->return_employer_nickname = null;
        $order->return_employer_phone = null;
        $order->return_employer_time = null;
        $order->save();
        return $this->success($renew);
    }
    //  线下租车      租车押金(deposit)+违章押金(break_rules)+基本保障(pre_base_price_total)+车辆整备费(bc_brokerage_total)
    private function allPrice($order,$base_pirce,$jp_price){
        return $base_pirce+$jp_price+$order->deposit+$order->break_rules+$order->pre_base_price_total+$order->bc_brokerage_total-$order->coupon_price;
    }
    //    获取部门
    public function getDepartment($id){
        Department::query()->where('id',$id)->value('name');
    }

    //临时更换数据
    public function templeChange(Request $request){
        $order = CarOrder::query()->where('order_sn',$request->order_sn)
            ->first();
        if(!$order){
            return $this->failed('订单不存在',201);
        }

        request()->offsetSet('pre_return_time',$order->pre_return_time);
        request()->offsetSet('pre_fetch_time',$order->pre_fetch_time);
//        获取车辆
        $this->car = $this->seriesCar($order->car_series_id);
        //总计价格
        $data = $this->totalPrice($request);
        list($bc_total,$deposit,$break_rules) = $this->computeBcTotal($request,$data);

        //随车饮料
        $order->drink = $request->drink;

//        实收押金
        $order->get_true_deport = $request->get_true_deport??0;
        //违章押金
        $order->violation_amount = $request->violation_amount??0;
        $order->deport_status = $request->deport_status;
        $order->break_rules_status = $request->break_rules_status;


        $order->bc_total = $bc_total;
        $order->save();
        return $this->success('更新成功');
    }

}
